package com.maijinjie.common.util;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.imageio.ImageIO;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
/**
 * 图片压缩处理工具
 * @version 1.0
 * @author 王欣逸
 */
public class ImgResize {
	/** 图片宽和高的最大尺寸 */
	public static final int MAX_BIG = 1200;
	/** 图片宽和高的最小尺寸 */
	public static final int MIN_BIG = 16;
	/** 按原图大小生成新图 */
	public static final int TYPE_FOR_COPY = 0;
	/** 按指定的大小生成新图 */
	public static final int TYPE_FOR_SIZE = 1;
	/** 按原图宽高比例生成新图-按指定的宽度 */
	public static final int TYPE_FOR_WIDTH = 2;
	/** 按原图宽高比例生成新图-按指定的高度 */
	public static final int TYPE_FOR_HEIGHT = 3;
	/** 按原图宽高比例生成新图-按指定的宽和高中较大的尺寸 */
	public static final int TYPE_FOR_MAX = 4;
	/** 按原图宽高比例生成新图-按指定的宽和高中较小的尺寸 */
	public static final int TYPE_FOR_MIN = 5;

	/**
	 * 创建新图片
	 * @param _file 原图片
	 * @param createType 处理类型
	 * @param newW 新宽度
	 * @param newH 新高度
	 * @param suffix 原图片文件名后面跟着的名字
	 * @return String 生成的新图片路径
	 * @throws IOException 
	 * @throws Exception
	 */
	public static String resize(File _file, int createType, int newW, int newH, String suffix) throws IOException {
		if (_file == null)
			return null;
		String imgPath = _file.getPath(); //原图片路径
		if (imgPath == null || "".equals(imgPath) || imgPath.lastIndexOf(".") == -1){
			return null;
		}
		//新图片路径
		String outImgPath = new StringBuffer(imgPath.substring(0, imgPath.lastIndexOf(".")))
				.append(suffix)
				.append(imgPath.substring(imgPath.lastIndexOf("."), imgPath.length())).toString();
		//图片后缀名
		String fileExtName = imgPath.substring((imgPath.lastIndexOf(".") + 1), imgPath.length());
		
		newW = checkMinAndMax(newW); //检查有无超出最大最小值
		newH = checkMinAndMax(newH); //检查有无超出最大最小值
		//原图是否存在且符合要求
		if (!_file.exists() || !_file.isAbsolute() || !_file.isFile() || !checkImageFile(fileExtName)){ 
			return null;
		}
		Image src;
		FileOutputStream out = null;
		try {
			src = ImageIO.read(_file);
	
			int[] wh = getSize(src, createType, newW, newH);//确定目标图片的大小
			int nw = wh[0];
			int nh = wh[1];
			
			if ((new File(outImgPath)).exists()) {//要生成的目标文件如果存在，则删除
				new File(outImgPath).delete();
			}
			
			// 构造目标图片
			BufferedImage tag = new BufferedImage(nw, nh, BufferedImage.TYPE_INT_RGB);
			// 得到目标图片输出流
			out = new FileOutputStream(outImgPath);
			// 根据需求画出目标图片 方式1
			tag.getGraphics().drawImage(src, 0, 0, nw, nh, null);
			// 将画好的目标图输出到输出流 方式1
			JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
			encoder.encode(tag);
		} catch (IOException e) {
			e.printStackTrace();
			throw e;
		} finally {
			if(null!=out){
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return outImgPath;
	}
	/**
	 * 检查最大和最小值设置
	 * @param n
	 * @return
	 */
	public static int checkMinAndMax(int n){
		if (n < MIN_BIG)
			n = MIN_BIG;
		else if (n > MAX_BIG)
			n = MAX_BIG;
		return n;
	}
	/**
	 * 获取生成目标大小，第0位为宽，第1位为高
	 * @param src
	 * @param createType
	 * @param newW
	 * @param newH
	 * @return int[] 第0位为宽，第1位为高
	 */
	public static int[] getSize(Image src, int createType, int newW, int newH){
		int w = src.getWidth(null);
		int h = src.getHeight(null);
		int[] size = new int[]{w,h};
		
		if (createType != TYPE_FOR_COPY){
			if (createType == TYPE_FOR_SIZE) {
				size[0] = newW;
				size[1] = newH;
			} else if (createType == TYPE_FOR_WIDTH) {
				size[0] = newW;
				size[1] = (int) ((double) h / (double) w * size[0]);
			} else if (createType == TYPE_FOR_HEIGHT) {
				size[1] = newH;
				size[0] = (int) ((double) w / (double) h * size[1]);
			} else if (createType == TYPE_FOR_MAX) {
				if ((double) w / (double) h >= (double) newW / (double) newH) {
					size[1] = newH;
					size[0] = (int) ((double) w / (double) h * size[1]);
				} else {
					size[0] = newW;
					size[1] = (int) ((double) h / (double) w * size[0]);
				}
			} else if (createType == TYPE_FOR_MIN) {
				if ((double) w / (double) h <= (double) newW / (double) newH) {
					size[1] = newH;
					size[0] = (int) ((double) w / (double) h * size[1]);
				} else {
					size[0] = newW;
					size[1] = (int) ((double) h / (double) w * size[0]);
				}
			}
		}
		return size;
	}

	/**
	 * 检查图片类型
	 * @param extName 图片扩展名
	 * @return boolean 是否属于图片类型文件
	 */
	public static boolean checkImageFile(String extName) {
		if ("jpg".equalsIgnoreCase(extName))
			return true;
		if ("gif".equalsIgnoreCase(extName))
			return true;
		if ("bmp".equalsIgnoreCase(extName))
			return true;
		if ("jpeg".equalsIgnoreCase(extName))
			return true;
		if ("png".equalsIgnoreCase(extName))
			return true;
		return false;
	}
}